package com.seadragon.app.ksr.util;

import org.apache.commons.lang.StringUtils;

import com.google.gson.ExclusionStrategy;
import com.google.gson.FieldAttributes;
import com.google.gson.GsonBuilder;
import com.vividsolutions.jts.geom.CoordinateSequence;
import com.vividsolutions.jts.geom.CoordinateSequenceFactory;

public class GsonUtils {

	public static String ObjectToGson(Object obj){
		return GsonUtils.ObjectToGson(obj,new ExclusionStrategy() {
			@Override
			public boolean shouldSkipField(FieldAttributes fa) {
				if ("parent".equals(fa.getName())) return true;//exclude the parent field to prevent circular reference
				else return false;
			}
			@Override
			public boolean shouldSkipClass(Class<?> clazz) {
				return clazz==null;
			}
		});
	}
	public static String ObjectToGson(Object obj, ExclusionStrategy strategy){
		String json = CustomConverters.registerAll(new GsonBuilder()
		.serializeNulls()
		.serializeSpecialFloatingPointValues()
		.setExclusionStrategies(strategy)
		.setDateFormat("yyyy-MM-dd"))
		.create()
		.toJson(obj);
		return StringUtils.replace(json, "NaN", "null");
	}
	
	public static String ObjectToGson(Object obj, String type){
		if ("category".equals(type)||"office".equals(type)||"business".equals(type)||"review".equals(type)){
			return GsonUtils.ObjectToGson(obj);
		}
		
		return GsonUtils.ObjectToGson(obj);
	}
	
	public static Object GsonToObject(String gson,Class<?> clazz,ExclusionStrategy strategy){
		Object obj = CustomConverters.registerAll(new GsonBuilder()
				.serializeNulls()
				.serializeSpecialFloatingPointValues()
				.setExclusionStrategies(strategy)
				.setDateFormat("yyyy-MM-dd"))
				.create().fromJson(gson, clazz);

		return obj;		
	}
	
	
	public static Object GsonToObject(String gson,Class<?> clazz){
		return GsonUtils.GsonToObject(gson, clazz,new ExclusionStrategy() {
			@Override
			public boolean shouldSkipField(FieldAttributes fa) {
				return false;
			}
			
			@Override
			public boolean shouldSkipClass(Class<?> clazz) {
				return CoordinateSequence.class.equals(clazz)||
						CoordinateSequenceFactory.class.equals(clazz);
			}
		});
	}
}
